package xjtu.sad.zbsj.task.publisher.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import xjtu.sad.zbsj.dao.task.TaskDao;
import xjtu.sad.zbsj.dao.task.TaskFileDao;
import xjtu.sad.zbsj.entity.TMark;
import xjtu.sad.zbsj.service.TMarkService;
import xjtu.sad.zbsj.task.publisher.Utils.ResultParam;
import xjtu.sad.zbsj.task.publisher.entity.Task;
import xjtu.sad.zbsj.task.publisher.params.DrawListRequestParams;
import xjtu.sad.zbsj.task.publisher.params.TaskListRequestParams;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskDao taskDao;
    @Autowired
    private TaskFileDao taskFileDao;
    @Autowired
    private TMarkService tMarkService;


    //添加任务
    @Override
    public ResultParam<Object> addTask(MultipartFile[] files, String publisher, String type,
                                       String templateId, String taskTitle, String taskRequire,
                                       String taskLimitTime, String taskMarkCount, String taskMaxDistribution,
                                       String taskExceptionTime, String taskDesc, String taskAward) {
        ResultParam<Object> result = new ResultParam<>();
        Task task = new Task();
        //ID
        String taskId = Long.toString(System.currentTimeMillis()).substring(6);
        //设置taskStatus为1 未分配
        task.setPublisher(publisher).setTaskKind(type).setTaskId(taskId).setTaskStatus("1").setTaskPublishTime(new Date())
                .setTemplateId(templateId).setTaskTitle(taskTitle).setTaskRequire(taskRequire).setTaskLimitTime(Integer.parseInt(taskLimitTime)).setTaskMarkCount(Integer.parseInt(taskMarkCount))
                .setTaskMaxDistribution(Integer.parseInt(taskMaxDistribution)).setTaskExceptionTime(Integer.parseInt(taskExceptionTime)).setTaskDesc(taskDesc)
                .setTaskAward(Integer.parseInt(taskAward));
        Integer integer = taskDao.addTask(task);
        if (integer > 0) {
            result.setStatus(200);
            result.setMsg("发布成功");
            result.setData(task.getTaskId());
//            if (files != null) {
//                for (int i = 0; i < files.length; i++) {
//                    String oldFileName = files[i].getOriginalFilename();
//                    //生成文件后缀
//                    String ext = "." + FilenameUtils.getExtension(files[i].getOriginalFilename());
//                    //生成新的文件名称
//                    String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + ext;
//                    //文件类型
//                    String fileType = files[i].getContentType();
//                    //生成目录
//                    try {
//                        String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/imga";
//                        realPath = URLDecoder.decode(realPath, "UTF-8");
//                        String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//                        String dateDirPath = realPath + "/" + dateFormat;
//                        File dateDir = new File(dateDirPath);
//                        if (!dateDir.exists()) {
//                            dateDir.mkdirs();//mkdirs()可以创建多级目录
//                        }
//                        //处理文件上传
//                        files[i].transferTo(new File(dateDir, newFileName));
//                        //将文件信息保存数据库中
//                        TaskFile taskFile = new TaskFile();
//                        taskFile.setTaskId(taskId).setFileUrl("/imga/" + dateFormat + "/" + newFileName).setFileType(fileType).setFileSize(Integer.parseInt(Long.toString(files[i].getSize())));
//                        Integer integer1 = taskFileDao.addFile(taskFile);
//                        if (integer1 > 0) {
//                            result.setStatus(200);
//                            result.setMsg("添加成功");
//                        } else {
//                            result.setMsg("添加失败");
//                            result.setStatus(404);
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        result.setStatus(404);
//                        result.setMsg("添加失败");
//                    }
//                }
//            }
        } else {
            result.setMsg("发布失败");
            result.setStatus(404);
        }
        return result;
    }

    @Override
    public ResultParam<Object> delTask(String taskId) {
        ResultParam<Object> result = new ResultParam<>();
        try {
            taskDao.delTask(taskId);
            result.setStatus(200);
            result.setMsg("删除成功");
        } catch (Exception e) {
            result.setStatus(500);
            result.setMsg("删除失败");
        }
        return result;
    }

    @Override
    public ResultParam<Object> taskList(TaskListRequestParams keyword, Integer userId) {
        String keyword1 = keyword.getKeyword();
        // 开启分页
        PageHelper.startPage(keyword.getCurrentPage(), keyword.getPageSize());
        List<Map<String, Object>> taskList = taskDao.taskList(keyword1, userId);
        for (Map<String, Object> stringObjectMap : taskList) {
            Object task_publish_time = stringObjectMap.get("task_publish_time");
            if (task_publish_time != null) {
                stringObjectMap.put("task_publish_time", LocalDateTime.parse(String.valueOf(task_publish_time)).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            Object task_status = stringObjectMap.get("task_status");
//            未分配、已分配、未审核、已结束'
            switch (Integer.valueOf(String.valueOf(task_status))) {
                case 1:
                    stringObjectMap.put("task_status", "分配中");
                    break;
                case 2:
                    stringObjectMap.put("task_status", "标注中");
                    break;
                case 3:
                    stringObjectMap.put("task_status", "未审核");
                    break;
                case 4:
                    stringObjectMap.put("task_status", "已结束");
                    break;
                default:
                    break;
            }
        }
        // 构建分页对象
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(taskList);
        ResultParam<Object> objectResultParam = new ResultParam<>();
        objectResultParam.setData(mapPageInfo);
        objectResultParam.setStatus(200);
        return objectResultParam;
    }

    @Override
    public ResultParam<Object> drawList(DrawListRequestParams drawListRequestParams) {
        // 开启分页
        PageHelper.startPage(drawListRequestParams.getCurrentPage(), drawListRequestParams.getPageSize());
        List<Map<String, Object>> drawList = taskDao.drawList(drawListRequestParams.getTaskId(), drawListRequestParams.getKeyword());
        for (Map<String, Object> stringObjectMap : drawList) {
            // 计算异常率
            //异常率：mark表里面的warning,1是异常，把一个draw对应的所有mark的warning值为1的加起来除以draw_num
            List<TMark> tMarks = tMarkService.queryByDrawId(Integer.valueOf(String.valueOf(stringObjectMap.get("draw_id"))));
            ListIterator<TMark> tMarkListIterator = tMarks.listIterator();
            while (tMarkListIterator.hasNext()) {
                TMark next = tMarkListIterator.next();
                if (next.getWarning() == null || (next.getWarning() != 1)) {
                    tMarkListIterator.remove();
                }
            }
            Optional<Integer> reduce = tMarks.stream()
                    .map(TMark::getWarning).reduce(Integer::sum);
            int exception = 0;
            Integer draw_num = Integer.valueOf(String.valueOf(stringObjectMap.get("draw_num")));
            if (reduce.isPresent()) {
                exception = reduce.get() * 100 / draw_num;
            }
//          抽样数：默认显示为draw_num乘5%，但是可以手动在列表里面输入进行修改
            if (stringObjectMap.get("sample") == null) {
                int sample = (int) (draw_num * 0.05);

                // 采样数
                stringObjectMap.put("sample", sample);
            }

            // 异常率 整数 不带%
            stringObjectMap.put("exception", exception);

            Object start_time = stringObjectMap.get("start_time");
            Object end_time = stringObjectMap.get("end_time");
            if (start_time != null) {
                stringObjectMap.put("start_time", LocalDateTime.parse(String.valueOf(start_time)).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            if (end_time != null) {
                stringObjectMap.put("end_time", LocalDateTime.parse(String.valueOf(end_time)).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            // 标注状态
            Object draw_status = stringObjectMap.get("draw_status");
            if (draw_status != null && !"".equalsIgnoreCase(String.valueOf(draw_status)) && !"null".equalsIgnoreCase(String.valueOf(draw_status))) {
                //           未完成，已完成，已审核，超时退回，无效
                switch (String.valueOf(draw_status)) {
                    case "WWC":
                        stringObjectMap.put("status", "未完成");
                        break;
                    case "YWC":
                        stringObjectMap.put("status", "已完成");
                        break;
                    case "YSH":
                        stringObjectMap.put("status", "已审核");
                        break;
                    case "CSTH":
                        stringObjectMap.put("status", "超时退回");
                        break;
                    case "WX":
                        stringObjectMap.put("status", "无效");
                        break;
                    default:
                        break;
                }
            }
        }
        // 构建分页对象
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(drawList);
        ResultParam<Object> objectResultParam = new ResultParam<>();
        objectResultParam.setData(mapPageInfo);
        objectResultParam.setStatus(200);
        return objectResultParam;
    }

    @Override
    public ResultParam<Object> cancel(String drawId) {
        taskDao.cancel(drawId);
        ResultParam<Object> objectResultParam = new ResultParam<>();
        objectResultParam.setMsg("撤回成功");
        objectResultParam.setStatus(200);
        return objectResultParam;
    }

    @Override
    public ResultParam<Object> end(String taskId) {
        taskDao.end(taskId);
        ResultParam<Object> objectResultParam = new ResultParam<>();
        objectResultParam.setMsg("成功");
        objectResultParam.setStatus(200);
        return objectResultParam;
    }

    @Override
    public void updateDrawSample(Integer drawId, Integer sample) {
        taskDao.updateDrawSample(drawId, sample);
    }
}

